<?php

namespace App\Http\Controllers\Guard\Student;

use App\Exports\AskExport;
use App\Exports\PointStudentExport;
use App\Exports\PointStudentFailExport;
use App\Http\Controllers\Common\GuardController;
use App\Imports\StudentPointImport;
use App\Mail\NoticeStudent;
use App\Models\Constant\StudentConstant;
use App\Models\Rbac\GuardUser;
use App\Models\School\School;
use App\Models\Student\Ask;
use App\Models\Student\College;
use App\Models\Student\Point;
use App\Models\Student\Student;
use App\Service\StudentService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Maatwebsite\Excel\Facades\Excel;

class StudentController extends GuardController {


    private $service;

    public function __construct() {
        $this->service = new StudentService(Student::class);
    }

    public function lst(Request $request) {
        $conditions = $request->input();


        $records = $this->service->lst($conditions)
            ->paginate($conditions['pageSize']??20,['*'],'page',$conditions['page']??1);

        $map_status = [['value'=>0,'label'=>'全部']];

        foreach (StudentConstant::MAP_STATUS as $k=>$v) {
            $map_status[] = [
                'value'=>$k,
                'label'=>$v,
            ];
        }

        return responseSuccess($records->items(),$records->total(),100000,compact('map_status'));
    }

    public function detail(Request $request) {
        $id = $request->input('id',0);
        $record = $this->service->detail($id);
        return responseSuccess([$record->toArray()],1);
    }

    public function del(Request $request) {
        $ids = $request->input('ids',[]);
        $this->service->del($ids);
        return responseSuccess();
    }

    public function askLst(Request $request) {
        $conditions = $request->input();

        $records = (new Ask())->getRecords($conditions)
            ->paginate($conditions['pageSize']??20,['*'],'page',$conditions['page']);

        return responseSuccess($records->items(),$records->total());

    }

    public function pointStudentLst(Request $request) {

        $conditions = $request->input();
        $records = (new Point())->getRecords($conditions)
            ->with('getGuardUser:id,name')
            ->paginate($conditions['pageSize']??20,['*'],'page',$conditions['page']);

        return responseSuccess($records->items(),$records->total());
    }

    /**
     * 下载成绩单
     * downloadPoint
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @Date:2022/11/8
     * @Author: Rudy
     */
    public function downloadPoint(Request $request) {
        $id = $request->input('id');
        $record = Student::where(compact('id'))->first();
        $url = $record->postgraduate_url;

        return response()->download(public_path($url));
    }

    /**
     * 导出咨询学生
     * askDownload
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @Date:2022/11/8
     * @Author: Rudy
     */
    public function askDownload(Request $request) {
        $conditions = $request->input();

        return Excel::download(new AskExport($conditions),'咨询.xlsx');
    }


    /**
     * 导入学生成绩
     * pointStudentImport
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     * @Date:2022/11/8
     * @Author: Rudy
     */
    public function pointStudentImport(Request $request) {
        $token = $request->input('token');
        $id = checkJWT($token)['id'];
        $guardUser = GuardUser::where(compact('id'))->first();

        if(empty($guardUser)){
            return responseFail('当前用户无效！');
        }
        $file = $request->file('file');
        if(empty($file) || !$file->isValid()){
            return responseFail('文件无效！');
        }
        $path = $file->store('point','upload');
        $import = new StudentPointImport($guardUser->id);
        Excel::import($import, storage_path('app/public/upload/'.$path));
        if($import->success){
            $countOK = $import->countOK;
            $countFail = $import->countFail;
            return responseSuccess(compact('countOK','countFail'),0,$import->msg);
        }else{
            return responseFail($import->msg);
        }
    }

    /**
     * 导出失败的学生名单
     * downloadPointFail
     * @param Request $request
     * @return \Symfony\Component\HttpFoundation\BinaryFileResponse
     * @throws \Exception
     * @Date:2022/11/8
     * @Author: Rudy
     */
    public function downloadPointFail(Request $request) {

        Log::info('downloadPointFail11111');
        $token = $request->input('token');
        $id = checkJWT($token)['id'];
        Log::info('downloadPointFail22222',[$id]);

        return Excel::download(new PointStudentFailExport($id),'失败名单.xlsx');
    }

    public function exportPointStudent(Request $request) {
        $conditions = $request->input();
        return Excel::download(new PointStudentExport($conditions),'学生成绩.xlsx');
    }

    public function interview(Request $request) {
        $ids = $request->input('ids',[]);
        $reviewTime = $request->input('time');
        $address = $request->input('address');
        $college = $request->input('college');

        $this->validate($request, [
            'ids'=>'required|array|min:0',
            'time'=>'required',
            'address'=>'required',
            'college'=>'required'
        ],[],[
            'ids'=>'学生',
            'time'=>'面试时间',
            'address'=>'地址',
            'college'=>'学校'
        ]);

        //dd($request->input());

        try{
            set_time_limit(-1);
            $info = [];
            $students = Student::whereIn('id',$ids)->get();
            foreach ($students as $student) {
                $name = $student->full_name;
                $email = $student->email;
                if(!empty($email)){
                    Mail::to($email)->send(new NoticeStudent($name,$college,$reviewTime,$address));
                }

                $student->status = StudentConstant::STATUS_INTERVIEW;
                $student->save();

                $info[] = ['student_id'=>$student->id,
                    'content'=>json_encode(compact('name','college','reviewTime','address'),JSON_UNESCAPED_UNICODE)];
            }

            DB::table('student_interview_log')->insert($info);

            return responseSuccess();
        }catch(\Exception $e){
            $tip = $e->getFile().':'.$e->getLine().':'.$e->getMessage();
            Log::error($tip);
            return responseFail();
        }


    }

    public function getCollege(Request $request){
        $records = School::get(['id as value','name as label']);
        return responseSuccess($records->toArray(),$records->count());
    }





}
